/* ContactListActivity.java
 *
 * Copyright 2011 Aleksey Konovalov
 * All Rights Reserved.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 * 
 */

package org.jimm.app;

import org.jimm.data.MainMenuProvider;
import org.jimm.engine.AccountsManager;
import org.jimm.im.Contact;
import org.jimm.service.Preferences;
import org.jimm.ui.MenuAdapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;




public class ContactListActivity extends Activity {
	
	
	
	public static final String LOG_TAG = "Jimm:ContactList";

	public static boolean ShowMenu; 
	private ContactListAdapter contactListAdapter;
	private SharedPreferences preferences;
	public static String lang;
	public static Context context;
	private static String ACTION = "org.jimm.ACTIONS";
	private static final String ACTIONS = "act";
	private static final int ACTION_EXIT = 1000;
	private static final int ACTION_DISCONNECT_ALL = 0;
	private static final int ACTION_CONNECT_ALL = 999;
	

	private void openChat(Contact contact) {
			
		try {
			contactListAdapter.update();
			Intent intent = new Intent(this, ChatActivity.class);
			intent.putExtra(ChatActivity.CONTACT_ID_EXTRA, contact.getID());
			intent.putExtra(ChatActivity.ACCOUNT_ID_EXTRA, contact.getAccount().getID());
			startActivity(intent);
		} catch (Exception e) {
			Log.e(LOG_TAG, "Error opening chat", e);
			e.printStackTrace();
		}
	}

	/** Called when the activity is first created. 
	 * @param Preferences */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_list);   
		
		JimmApplication.appStarted=true;
		
		context=getApplicationContext();
		
		ShowMenu=true;		
	
		contactListAdapter = new ContactListAdapter(this);
		ExpandableListView contactList = (ExpandableListView) ContactListActivity.this
				.findViewById(R.id.ContactList);
		contactList.setAdapter(contactListAdapter);	
		contactList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition,
					int childPosition, long id) {
				Contact contact = contactListAdapter.getChild(groupPosition, childPosition);
				if (contact != null)
					openChat(contact);
				return true;
			}
		});		
		
		// TODO count acc
		TextView text = (TextView) findViewById(R.id.text);
		text.setText("");
				
		
		//int count = AccountsEditorActivity.getCount();
		ImageView setting =  (ImageView) findViewById(R.id.setting);
		ImageView dis =  (ImageView) findViewById(R.id.dis);
		ImageView con =  (ImageView) findViewById(R.id.con);
		setting.setOnClickListener(new View.OnClickListener(){  
            public void onClick(View v){
            	//startActivity(new Intent(getApplicationContext(), SettingsActivity.class));
            	ShowMenu=true;
            	ShowMenuFunc();
            }});
		dis.setOnClickListener(new View.OnClickListener(){  
            public void onClick(View v){
            	AccountsManager man = JimmApplication.getApplication(
	    				ContactListActivity.this).getAccountsManager();
	    		if (man != null)
	    			man.disconnectAll();
	    		Toast.makeText(getApplicationContext(), "Disconnect", Toast.LENGTH_SHORT).show();
            }});
		con.setOnClickListener(new View.OnClickListener(){  
            public void onClick(View v){
            	connectAll();
            }});
		
		ShowMenuFunc();
		
	}
	
	public void Sound() {	
		boolean se = Preferences.soundEnabled;		
		if (se) setVolumeControlStream(AudioManager.STREAM_MUSIC);
		else setVolumeControlStream(AudioManager.USE_DEFAULT_STREAM_TYPE);
	}
	
	public boolean onKey(View v, int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event){	
        if (keyCode == KeyEvent.KEYCODE_MENU){
		ShowMenu=true;
		ShowMenuFunc();
        }
        if (keyCode == KeyEvent.KEYCODE_BACK){
    		moveTaskToBack (true);
            }
        return false;        
    }
			
	public static void showSelectMenuItemDialog(Activity context, int title, OnClickListener dialogListener) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(title);
        builder.setAdapter(new MenuAdapter(context, MainMenuProvider.iconMenu), dialogListener);
        builder.create().show();
      }
	
	public void ShowMenuFunc() {
	if (ShowMenu) {
		showSelectMenuItemDialog(this, R.string.MainMenu, new OnClickListener() {
	          @Override
	          public void onClick(DialogInterface dialogInterface, int selectedItemId) {
	            if(selectedItemId==0) {
	            	connectAll();
				}
		    	if(selectedItemId==1) {
		    		startActivity(new Intent(ContactListActivity.this, SettingsActivity.class));
		    	}
		    	if(selectedItemId==2) {
		    		startActivity(new Intent(ContactListActivity.this, AboutActivity.class));
		    	}
		    	if(selectedItemId==3) {
		    		Intent intent = new Intent(ACTION);
	                intent.putExtra(ACTIONS, ACTION_EXIT);
	               // sendBroadcast(intent);
	                JimmApplication.closeApp();
					finish();
					//JimmApplication.getApplication(ContactListActivity.this).exit();
		    	}
	          }
	        });
	}
	
	//TODO if click MENU, then dialog dismiss();
	ShowMenu=false;
  	};
	
  	/*
	protected void onPause() {
		super.onPause();
		Log.i(LOG_TAG, "onPause");
	}
	
	
	protected void onRestart(Bundle savedInstanceState) {
		super.onRestart();
		onRestoreInstanceState(savedInstanceState);
		Log.i(LOG_TAG, "onRestart" + savedInstanceState); 	
	}
	
	protected void onStop(Bundle savedInstanceState) {
		super.onStop();
		onSaveInstanceState(savedInstanceState);
		Log.i(LOG_TAG, "onStop" + savedInstanceState);
	}
	
	protected void onResume(Bundle savedInstanceState) {
		super.onResume();
		onRestoreInstanceState(savedInstanceState);
		
		Log.i(LOG_TAG, "ShowMenuResume"+ShowMenu);
		if (ShowMenu) {ShowMenuFunc();};
		Log.i(LOG_TAG, "onResume" + savedInstanceState); 	
	}
	*/
	
	void connectAll() {
		if (InitializeActivity.needAcc(context)) {
			ShowMenu=true;
			startActivity(new Intent(this, AccountsEditorActivity.class));
			} else {
			AccountsManager man = JimmApplication.getApplication(
    				ContactListActivity.this).getAccountsManager();
    		if (man != null)
    			man.connectAll();
    		Toast.makeText(getApplicationContext(), R.string.Connection, Toast.LENGTH_SHORT).show();
			
		}
	}
	
	protected void onResume() {
		super.onResume();
		//TODO if prefence sound=true
		Sound();
		if (ShowMenu) {ShowMenuFunc();};
	
	}
	
	@Override
    public void onConfigurationChanged(Configuration newConfiguration)
    {
        super.onConfigurationChanged(newConfiguration);
    }
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		contactListAdapter.uninitialize();
	}		
}
